<template>
  <div>
    <van-cell>
      <div class="cmt-box">
        <!-- 头像 -->
        <van-image fit="cover" round :src="item.aut_photo" />
        <!-- 内容 -->
        <div class="center-box">
          <div class="name">{{ item.aut_name }}</div>
          <div class="content">{{ item.content }}</div>
          <div class="time-box">
            <span class="time">{{ item.pubdate | formatTime }}</span>
          </div>
        </div>
      </div>
    </van-cell>

    <van-divider>回复列表</van-divider>
    <!-- 放list -->
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <van-cell v-for="item in list" :key="item.com_id">
        <div class="cmt-box">
          <!-- 头像 -->
          <van-image fit="cover" round :src="item.aut_photo" />
          <!-- 内容 -->
          <div class="center-box">
            <div class="name">{{ item.aut_name }}</div>
            <div class="content">{{ item.content }}</div>
            <div class="time-box">
              <span class="time">{{ item.pubdate | formatTime }}</span>
            </div>
          </div>

        </div>
      </van-cell>
    </van-list>

    <!-- 放输入框 -->
    <div class="input-box">
      <van-field
        @keyup.enter="send"
        v-model="cmt"
        center
        clearable
        placeholder="请输入评论内容"
      >
        <template #button>
          <van-button @click="send" size="small" type="info">发布</van-button>
        </template>
      </van-field>
    </div>
  </div>
</template>

<script>
import { getCmtListAPI, sendCmtAPI } from '@/api/comment'

export default {
  props: {
    item: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      cmt: '',
      offset: null
    }
  },
  methods: {
    async send () {
      // 非空判断
      if (this.cmt === '') return this.$toast('请输入内容')

      // 能来到这代表有内容，就应该发请求
      const res = await sendCmtAPI({
        // 如果是回复，传评论id
        target: this.item.com_id,
        content: this.cmt,
        art_id: this.$route.params.id
      })

      // 把新增成功的评论加到数组里的前面
      this.list.unshift(res.data.new_obj)
      // 让当前评论的回复数+1
      this.$emit('add')
      // 清空输入的内容
      this.cmt = ''
    },
    async onLoad () {
      const res = await getCmtListAPI({
        // 获取评论的回复，传c
        type: 'c',
        // 传评论id
        source: this.item.com_id,
        // 传null代表查第一页
        offset: this.offset
      })

      // 把数据加到数组
      this.list.push(...res.data.results)

      // 把last_id存到offset里，下次就能从这条id后面开始查询
      this.offset = res.data.last_id

      // 结束本次加载状态
      this.loading = false

      // 判断是否全部加载完
      if (this.list.length >= res.data.total_count) {
        this.finished = true
      }
    }
  }
}
</script>

<style></style>
